<?php
namespace App\Workerman;

include_once(__DIR__ . '/../../vendor/autoload.php');

use GatewayWorker\Lib\Gateway;
use Curl\Curl as C;

(\Dotenv\Dotenv::createImmutable(__DIR__ . '/../../'))->load();//加载.env文件
$onStartParameter = [];

/**
 * 主进程不做 redis/mysql 服务
 * Class Events
 * @package App\Workerman
 */
class Events
{
    private static $api = '/api';

    private static $start = '/start';

    private static $ignoreSymbol = ['\\','/'];

    public static function onWorkerStart($businessWorker):void
    {
        $start_memory = memory_get_usage();//开始内存
        global $onStartParameter;
        $onStartParameter = compact($businessWorker);
        include_once(__DIR__ . "/../Http/Controllers/StartServer.php");
        //开启所有定时器
        \App\Libs\Timer::run([//绑定事件必须带上调用Timer时带上key作为绑定
            'randomIntoRoom',//机器人自动进入房间
            'setAllResultData',//设置所有开奖数据(todo 第一版通过自身采集网站,第二版是服务端发送开奖给自身 所以无效化)
            'automaticBet',//机器人自动开奖
            'updateOpenResult',//更新开奖时间
            'openResult',//发送开奖信息到客户端
        ]);//定时器抑制器

        self::memory($start_memory);//计算内存占用情况
    }

    /**
     * 计算内存占用情况
     * @param $start_memory
     */
    public static function memory($start_memory)
    {
        dump("开始计算内存占用====>".date('Y-m-d H:i:s',time()));
        \Workerman\Lib\Timer::add(60,function() use ($start_memory){//监听当前的内存占用
            $end_memory = memory_get_usage();//开始内存
            dump("当前占用内存情况:".getFileSize($end_memory-$start_memory)."||".date('Y-m-d H:i:s',time()));
        });
    }

    /**
     * 数据处理
     * @param $client_id
     * @param $message
     */
    public static function onMessage($client_id, $message):void
    {
        $mes = jsonToArray($message);//json
        if ($mes) {
            if(isset($mes['f']) && !empty($mes['f'])) {
                $url = trimList($_ENV['DOMAIN'],self::$ignoreSymbol) . self::$api . '/' . trimList($mes['f'],self::$ignoreSymbol);
            }else{
                $url = trimList($_ENV['DOMAIN'],self::$ignoreSymbol) . self::$api . '/';
            }
            //路由访问规则
            $curl = new C();
            $curl->post($url,[
                'client_id' => $client_id,
                'message' => $mes
            ]);
            $code = $curl->getHttpStatusCode();
            if($code == 200) {
                //成功
                if($curl->response) {
                    var_dump($curl->response);
                }
            } else {
                Gateway::sendToClient($client_id,toJson([
                    'code' => $code,
                    'message' => '非法请求~'
                ]));
            }
            $curl->close();//关闭请求
        }
    }

    public static function onConnect($client_id){}

    public static function onWebSocketConnect($client_id, $data){}

    public static function onClose($client_id){}
}
